class Feriado < ActiveRecord::Base
  belongs_to :sucursal
  validates_presence_of :nombre,:fecha
  named_scope :find_by_fecha, lambda{|fecha| {:conditions=>["(day=? and month=? and year is null) or (day=? and month=? and year=?)",fecha.day,fecha.month,fecha.day,fecha.month,fecha.year]}}
  named_scope :find_by_month, lambda{|fecha| {:conditions=>["(month=? and year is null) or (and month=? and year=?)",fecha.month,fecha.month,fecha.year]}}
  named_scope :find_all_by_year, lambda{|year| {:conditions=>["year=?",year]}}
  named_scope :find_all_by_sucursal_id, lambda{|sucursal_id| {:conditions=>["sucursal_id IS NULL or sucursal_id=?",sucursal_id]}}
  PROMPT="Repetir anualmente"
  def fecha(show_month_names=false)
    self.year ? year="/#{self.year}" : repeat="#{PROMPT} el "
    month = show_month_names ? " de #{UtilHelper.mes_nombre(self.month)}" : "/#{self.month}"
    "#{repeat} #{self.day}#{month}#{year}"
  end
  
  def index
    self.year.to_s<<'-'<<self.month.to_s<<'-'<<self.day.to_s<<'-'<<self.sucursal_id
  end
  
  def self.find_all_by_periodo(desde,hasta,sucursal_id=nil)
    fechas=[]
    desde.upto(hasta){|fecha| fechas<<"(day=#{fecha.day} and month=#{fecha.month} and year is null) or (day=#{fecha.day} and month=#{fecha.month} and year=#{fecha.year})"}    
    scope=self.find_all_by_sucursal_id(sucursal_id) if sucursal_id
    scope.find(:all,:conditions=>fechas.join(' or '))
  end
end
